<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="templateId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="addTask">新增</el-button>
        <el-button type="primary" :icon="EditPen" @click="editSLA(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedList)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="editTemplateNameBtn([scope.row])">编辑模板名称</el-button>
        <el-button type="primary" link :icon="EditPen" @click="editSLA([scope.row])">编辑模板内容</el-button>
        <el-button type="primary" link :icon="Delete" @click="batchDelete([scope.row])">删除</el-button>
      </template>
    </ProTable>
    <el-dialog v-model="editTemplateNameDialogVisible" title="编辑内容模板名称" width="30%">
      <el-form style="width: 100%" label-width="120px">
        <el-form-item label="内容模板名称 :" prop="etitle">
          <el-input v-model="editTemplateNameFormData.templateName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="saveTemplateName">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog title="类型" v-model="dialogTableVisible">
      <div :style="{ height: '300px' }">
        <div>
          <el-radio v-model="scheduledTaskType" label="request">请求内容模板</el-radio>
        </div>
        <div>
          <el-radio v-model="scheduledTaskType" label="problem">问题内容模板</el-radio>
        </div>
        <div>
          <el-radio v-model="scheduledTaskType" label="change">变更内容模板</el-radio>
        </div>
        <div>
          <el-radio v-model="scheduledTaskType" label="configureItem">配置项内容模板</el-radio>
        </div>
        <div>
          <el-radio v-model="scheduledTaskType" label="knowledge">知识库内容模板</el-radio>
        </div>
      </div>
      <el-button type="primary" @click="onSubmit()"> 确认选择 </el-button>
    </el-dialog>
    <el-dialog :title="AddDtlName" v-model="dialogAddDtlVisible">
      <div :style="{ height: '620px' }">
        <el-form style="width: 100%" label-width="120px">
          <el-form-item label="标题 :" prop="etitle">
            <el-input v-model="addDtlFormData.etitle" />
          </el-form-item>
          <el-form-item label="" prop="etitle">
            <table style="width: 100%">
              <tr>
                <td><el-radio v-model="addDtlFormData.timeType" label="day">日计划</el-radio></td>
                <td><el-radio v-model="addDtlFormData.timeType" label="weekly">周计划</el-radio></td>
                <td><el-radio v-model="addDtlFormData.timeType" label="month">月计划</el-radio></td>
              </tr>
              <tr>
                <td><el-radio v-model="addDtlFormData.timeType" label="cycle">周期性计划（天）</el-radio></td>
                <td><el-radio v-model="addDtlFormData.timeType" label="cycleMinute">周期性计划（分钟）</el-radio></td>
                <td><el-radio v-model="addDtlFormData.timeType" label="on_off">一次性计划</el-radio></td>
              </tr>
            </table>
          </el-form-item>

          <div v-if="addDtlFormData.timeType == `day`">
            <el-form-item label="[每日定时任务]"> </el-form-item>
            <el-form-item label="开始时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskEndDate"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="具体时间 :">
              <el-input-number v-model="addDtlFormData.taskHour" :min="0" :max="23" />点
              <el-input-number v-model="addDtlFormData.taskMinute" :min="0" :max="59" />分
            </el-form-item>
          </div>
          <div v-if="addDtlFormData.timeType == `weekly`">
            <el-form-item label="[每周定时任务]"> </el-form-item>
            <el-form-item label="">
              <table style="width: 100%">
                <tr>
                  <td><el-checkbox v-model="meizhou" label="selectmeizhou" @change="changeMeizhou">每周：</el-checkbox></td>
                </tr>
                <tr>
                  <td><el-checkbox v-model="addDtlFormData.MON" label="MON">星期一</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.TUE" label="TUE">星期二</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.WED" label="WED">星期三</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.THU" label="THU">星期四</el-checkbox></td>
                </tr>
                <tr>
                  <td><el-checkbox v-model="addDtlFormData.FRI" label="FRI">星期五</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.SAT" label="SAT">星期六</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.SUN" label="SUN">星期天</el-checkbox></td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="开始时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskEndDate"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="具体时间 :">
              <el-input-number v-model="addDtlFormData.taskHour" :min="0" :max="23" />点
              <el-input-number v-model="addDtlFormData.taskMinute" :min="0" :max="59" />分
            </el-form-item>
          </div>

          <div v-if="addDtlFormData.timeType == `month`">
            <el-form-item label="[每月定时任务]   ">
              <el-checkbox v-model="meiyue" label="selectmeiyue" @change="changeMeiyue">每月：</el-checkbox>
            </el-form-item>
            <el-form-item label="">
              <table style="width: 100%">
                <!-- <tr>
		  							   <td><el-checkbox v-model="meiyue" label="selectmeiyue"  @change="changeMeiyue">每月：</el-checkbox></td>
		  						   </tr> -->
                <tr>
                  <td><el-checkbox v-model="addDtlFormData.JAN" label="JAN" @change="changeYue">一月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.FEB" label="FEB" @change="changeYue">二月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.MAR" label="MAR" @change="changeYue">三月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.APR" label="APR" @change="changeYue">四月</el-checkbox></td>
                </tr>
                <tr>
                  <td><el-checkbox v-model="addDtlFormData.MAY" label="MAY" @change="changeYue">五月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.JUN" label="JUN" @change="changeYue">六月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.JUL" label="JUL" @change="changeYue">七月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.AUG" label="AUG" @change="changeYue">八月</el-checkbox></td>
                </tr>
                <tr>
                  <td><el-checkbox v-model="addDtlFormData.SEP" label="SEP" @change="changeYue">九月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.OCT" label="OCT" @change="changeYue">十月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.NOV" label="NOV" @change="changeYue">十一月</el-checkbox></td>
                  <td><el-checkbox v-model="addDtlFormData.DEC" label="DEC" @change="changeYue">十二月</el-checkbox></td>
                </tr>
                <tr>
                  <td colspan="4">
                    <div class="no-wrap">
                      日期：
                      <el-select v-model="addDtlFormData.monthDay" placeholder="Select" style="width: 100px">
                        <el-option v-for="item in monthDayNum" :key="item" :label="item" :value="item" />
                      </el-select>
                    </div>
                    <span> </span>
                  </td>
                </tr>
              </table>
            </el-form-item>
            <el-form-item label="具体时间 :">
              <el-input-number v-model="addDtlFormData.taskHour" :min="0" :max="23" />点
              <el-input-number v-model="addDtlFormData.taskMinute" :min="0" :max="59" />分
            </el-form-item>
          </div>
          <div v-if="addDtlFormData.timeType == `cycle`">
            <el-form-item label="[周期性计划(天)]"> </el-form-item>
            <el-form-item label="每">
              <el-input-number v-model="addDtlFormData.cyclicalDay" :min="1" :max="99999" />天执行一次
            </el-form-item>
            <el-form-item label="开始时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskEndDate"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="具体时间 :">
              <el-input-number v-model="addDtlFormData.taskHour" :min="0" :max="23" />点
              <el-input-number v-model="addDtlFormData.taskMinute" :min="0" :max="59" />分
            </el-form-item>
          </div>
          <div v-if="addDtlFormData.timeType == `cycleMinute`">
            <el-form-item label="[周期性计划(分钟)]"> </el-form-item>
            <el-form-item label="每">
              <el-input-number v-model="addDtlFormData.cyclicalMinute" :min="1" :max="99999" />分钟执行一次
            </el-form-item>
            <el-form-item label="开始时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskEndDate"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </div>
          <div v-if="addDtlFormData.timeType == `on_off`">
            <el-form-item label="[只执行一次]"> </el-form-item>
            <el-form-item label="开始时间 :">
              <el-date-picker
                v-model="addDtlFormData.taskDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="具体时间 :">
              <el-input-number v-model="addDtlFormData.taskHour" :min="0" :max="23" />点
              <el-input-number v-model="addDtlFormData.taskMinute" :min="0" :max="59" />分
            </el-form-item>
          </div>
        </el-form>
      </div>
      <el-button type="primary" @click="onSubmitAddDtl()"> 保存 </el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useTabsStore } from "@/stores/modules/tabs";
import { User, RoleManager, OrgManager } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/accessControl/roleManagement/components/RoleDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import { getUserDepartment } from "@/api/modules/jggl";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import {
  FindSlaContractManagePage,
  getUserDepartmentList,
  editSlaContractManage,
  saveSlaContractManage,
  deleteSlaContractManage,
  findSlaById,
  findByServiceDir,
  findByOrgServices
} from "@/api/modules/slaProtocolManagement";
import { getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  findPagerContentTemplate,
  editTemplateName,
  deleteContentTemplate
} from "@/api/modules/systemTools";
const route = useRoute();
const tabStore = useTabsStore();
const router = useRouter();
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });
const addDtlFormData = reactive({
  reportId: 0,
  scheduledTaskId: "",
  scheduledTaskType: "",
  beanId: "autoUpdateRequestJob",
  companyNo: 1,
  etitle: "",
  timeType: "day",
  cyclicalDay: 1,
  cyclicalMinute: 1,
  taskDate: "",
  taskEndDate: "",
  taskHour: 0,
  taskMinute: 0,
  MON: false,
  TUE: false,
  WED: false,
  THU: false,
  FRI: false,
  SAT: false,
  SUN: false,

  JAN: false,
  FEB: false,
  MAR: false,
  APR: false,
  MAY: false,
  JUN: false,
  JUL: false,
  AUG: false,
  SEP: false,
  OCT: false,
  NOV: false,
  DEC: false,
  monthDay: 1
});
// ProTable 实例
const proTable = ref<ProTableInstance>();
const meizhou = ref("");
const meiyue = ref("");
const monthDayNum = ref(31);

const scheduledTaskType = ref("request");
const dialogTableVisible = ref(false);
const dialogAddDtlVisible = ref(false);
const AddDtlName = ref("");
const TaskOption = ref("");

const changeYue = async value => {
  addDtlFormData.monthDay = 1;
  if (addDtlFormData.FEB == true) {
    monthDayNum.value = 28;
  } else {
    if (addDtlFormData.APR == true || addDtlFormData.JUN == true || addDtlFormData.SEP == true || addDtlFormData.NOV == true) {
      monthDayNum.value = 30;
    } else {
      monthDayNum.value = 31;
    }
  }
};
// 每月是否选择
const changeMeiyue = async value => {
  if (value == true) {
    addDtlFormData.JAN = true;
    addDtlFormData.FEB = true;
    addDtlFormData.MAR = true;
    addDtlFormData.APR = true;
    addDtlFormData.MAY = true;
    addDtlFormData.JUN = true;
    addDtlFormData.JUL = true;
    addDtlFormData.AUG = true;
    addDtlFormData.SEP = true;
    addDtlFormData.OCT = true;
    addDtlFormData.NOV = true;
    addDtlFormData.DEC = true;
  } else {
    addDtlFormData.JAN = false;
    addDtlFormData.FEB = false;
    addDtlFormData.MAR = false;
    addDtlFormData.APR = false;
    addDtlFormData.MAY = false;
    addDtlFormData.JUN = false;
    addDtlFormData.JUL = false;
    addDtlFormData.AUG = false;
    addDtlFormData.SEP = false;
    addDtlFormData.OCT = false;
    addDtlFormData.NOV = false;
    addDtlFormData.DEC = false;
  }
};
// 每周是否选择
const changeMeizhou = async value => {
  if (value == true) {
    addDtlFormData.MON = true;
    addDtlFormData.TUE = true;
    addDtlFormData.WED = true;
    addDtlFormData.THU = true;
    addDtlFormData.FRI = true;
    addDtlFormData.SAT = true;
    addDtlFormData.SUN = true;
  } else {
    addDtlFormData.MON = false;
    addDtlFormData.TUE = false;
    addDtlFormData.WED = false;
    addDtlFormData.THU = false;
    addDtlFormData.FRI = false;
    addDtlFormData.SAT = false;
    addDtlFormData.SUN = false;
  }
};
const onSubmit = async () => {
  // request problem change configureItem knowledge
  if (scheduledTaskType.value == "request") {
    //前往请求添加页面
    tabStore.removeTabs(route.fullPath);
    router.push(`/system/tools/contentTemplateManagement/addRequestContentTemplate?pageNo=${Math.random().toFixed(3)}`);
    dialogTableVisible.value = false;
    return;
  }
  if (scheduledTaskType.value == "problem") {
    //前往请求添加页面
    tabStore.removeTabs(route.fullPath);
    router.push(`/system/tools/contentTemplateManagement/addProblemTemplateForm?pageNo=${Math.random().toFixed(3)}&id=111`);
    dialogTableVisible.value = false;
    return;
  }
  if (scheduledTaskType.value == "change") {
    //前往添加页面
    tabStore.removeTabs(route.fullPath);
    router.push(`/system/tools/contentTemplateManagement/addChangeTemplateForm?pageNo=${Math.random().toFixed(3)}`);
    dialogTableVisible.value = false;
    return;
  }
  if (scheduledTaskType.value == "configureItem") {
    //前往添加页面
    tabStore.removeTabs(route.fullPath);
    router.push(`/system/tools/contentTemplateManagement/addCiTemplateForm?pageNo=${Math.random().toFixed(3)}`);
    dialogTableVisible.value = false;
    return;
  }
  if (scheduledTaskType.value == "knowledge") {
    //前往添加页面
    tabStore.removeTabs(route.fullPath);
    router.push(`/system/tools/contentTemplateManagement/addKnowledgeTemplateForm?pageNo=${Math.random().toFixed(3)}`);
    dialogTableVisible.value = false;
    return;
  }
  if (scheduledTaskType.value == "sla") {
    AddDtlName.value = "SLA到期自动升级";
  }
  if (scheduledTaskType.value == "email") {
    AddDtlName.value = "请求邮件定期扫描";
  }
  if (scheduledTaskType.value == "request2problem") {
    AddDtlName.value = "请求过期自动转化为问题";
  }
  if (scheduledTaskType.value == "configureItem") {
    AddDtlName.value = "配置项三类过期的检测";
  }
  if (scheduledTaskType.value == "senReport") {
    AddDtlName.value = "自动发送报表";
  }
  if (scheduledTaskType.value == "adUpdate") {
    AddDtlName.value = "活动目录(AD)同步更新";
  }
  dialogTableVisible.value = false;
  dialogAddDtlVisible.value = true;
  TaskOption.value = "add";
};

const onSubmitAddDtl = async () => {
  if (addDtlFormData.etitle == "") {
    ElMessage.error("请填写标题");
    return;
  }

  if (addDtlFormData.timeType == `month`) {
    //月的时候时间不用填
    addDtlFormData.taskDate = "";
    addDtlFormData.taskEndDate = "";
  } else {
    if (addDtlFormData.taskDate == "") {
      ElMessage.error("请选择开始时间");
      return;
    }

    if (addDtlFormData.timeType == `on_off`) {
    } else {
      if (addDtlFormData.taskEndDate == "") {
        ElMessage.error("请选择结束时间");
        return;
      }
    }
  }
  if (addDtlFormData.timeType != `on_off`) {
    let taskDate = new Date(addDtlFormData.taskDate);
    let taskEndDate = new Date(addDtlFormData.taskEndDate);
    if (taskDate >= taskEndDate) {
      ElMessage.error("开始时间不能大于结束时间");
      return;
    }
  }

  addDtlFormData.scheduledTaskType = scheduledTaskType.value;

  if (addDtlFormData.timeType != `on_off`) {
    let selsctDate = new Date(addDtlFormData.taskEndDate);
    let year = selsctDate.getFullYear(); // 获取当前年份
    let month = selsctDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
    let day = selsctDate.getDate();
    let selsctTime = new Date(year, month, day);
    let nowDate = new Date();
    let nowDateyear = nowDate.getFullYear(); // 获取当前年份
    let nowDatemonth = nowDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
    let nowDateday = nowDate.getDate();
    let nowTime = new Date(nowDateyear, nowDatemonth, nowDateday);
    if (selsctTime <= nowTime) {
      ElMessage.error("设置的任务执行时间不能早于当前系统时间!");
      return;
    }
  } else {
    let selsctDate = new Date(addDtlFormData.taskDate);
    let year = selsctDate.getFullYear(); // 获取当前年份
    let month = selsctDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
    let day = selsctDate.getDate();
    let selsctTime = new Date(year, month, day);
    let nowDate = new Date();
    let nowDateyear = nowDate.getFullYear(); // 获取当前年份
    let nowDatemonth = nowDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，需要加1
    let nowDateday = nowDate.getDate();
    let nowTime = new Date(nowDateyear, nowDatemonth, nowDateday);
    if (selsctTime <= nowTime) {
      ElMessage.error("设置的任务执行时间不能早于当前系统时间!");
      return;
    }
  }
  try {
    if (TaskOption.value == "add") {
      saveScheduledTask(addDtlFormData, "scheduledTaskDTO", "").then(res => {
        console.log(res);
        ElMessage.success("新增成功");
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    } else {
      editScheduledTask(addDtlFormData, "scheduledTaskDTO", "").then(res => {
        console.log(res);
        ElMessage.success("编辑成功");
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    }
  } catch (e) {}

  dialogAddDtlVisible.value = false;

  console.log(addDtlFormData);
};
const editTemplateNameDialogVisible = ref(false);
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // if (newParams.createTime != undefined) {
  //   newParams.startCreateTime = newParams.createTime[0];
  //   newParams.endCreateTime = newParams.createTime[1];
  //   delete newParams.createTime;
  // }
  // if (newParams.lastUpdateTime != undefined) {
  //   newParams.startUpdateTime = newParams.lastUpdateTime[0];
  //   newParams.endUpdateTime = newParams.lastUpdateTime[1];
  //   delete newParams.lastUpdateTime;
  // }
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "templateId";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findPagerContentTemplate(newParams, "templateDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

export interface resList {
  // agreement: string;
  // beginTime: string;
  // byServicesNos: [1, 2];
  // string: string;
  // companyNo: number;
  // contractName: string;
  // contractNo: number;
  // dataFlag: number;
  // dcode: number;
  // dname: string;
  // endTime: string;
  // isDefault: boolean;
  // lastUpdater: string;
  // rulePackageNo: number;
  // serviceDirNos: [];
  // serviceOrgName: string;
  // serviceOrgNo: number;
  // versionNumber: string;
  // orgNo: string;
  // orgName: string;

  companyName: string;
  // createTime: string;
  // description: string;
  // lastUpdateTime: string;
  scheduledTaskId: number;
  scheduledTaskType: string;
  taskDate: string;
  taskEndDate: string;
  timeType: string;
  title: string;

  categoryNo: number;
  companyNo: number;
  createTime: string;
  creator: string;
  dataFlag: number;
  description: string;
  formId: number;
  indexContent: string;
  isNewForm: boolean;
  isShowBorder: string;
  lastUpdateTime: string;
  lastUpdater: string;
  optimisticLock: number;
  remark: string;
  serviceDirId: number;
  templateId: number;
  templateJson: string;
  templateName: string;
  templateType: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "templateId", label: "ID", sortable: true, width: 80 },
  { prop: "templateName", label: "内容模板名称", search: { el: "input" }, sortable: true },
  {
    prop: "templateType",
    label: "类型",
    sortable: true,
    width: 160,
    enum: [
      {
        genderLabel: "请求内容模板",
        genderValue: "request"
      },
      {
        genderLabel: "问题内容模板",
        genderValue: "problem"
      },
      {
        genderLabel: "变更内容模板",
        genderValue: "change"
      },
      {
        genderLabel: "配置项内容模板",
        genderValue: "configureItem"
      },
      {
        genderLabel: "知识库内容模板",
        genderValue: "knowledge"
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => (
      <>
        {scope.row.templateType === "request"
          ? "请求内容模板"
          : scope.row.templateType === "problem"
            ? "问题内容模板"
            : scope.row.templateType === "change"
              ? "变更内容模板"
              : scope.row.templateType === "configureItem"
                ? "配置项内容模板"
                : scope.row.templateType === "knowledge"
                  ? "知识库内容模板"
                  : "未定义类型"}
      </>
    )
  },
  { prop: "operation", label: "操作", fixed: "right", width: 360 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  ElMessage.success("修改列表排序成功");
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?templateIds=" + id[i].templateId;
    } else {
      idsStr = idsStr + "&templateIds=" + id[i].templateId;
    }
    NameStr = NameStr + id[i].templateName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      deleteContentTemplate(idsStr).then(res => {
        if (res == null) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          proTable.value?.clearSelection();
          proTable.value?.getTableList();
        } else {
          ElMessage({
            type: "error",
            message: "存在关联数据无法删除，请检查"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const addTask = () => {
  dialogTableVisible.value = true;
};
const editTemplateNameFormData = reactive({
  templateId: 0,
  templateName: ""
});
const editTemplateNameBtn = async (params: any[]) => {
  editTemplateNameFormData.templateId = params[0].templateId;
  editTemplateNameFormData.templateName = params[0].templateName;
  editTemplateNameDialogVisible.value = true;
};
const saveTemplateName = () => {
  editTemplateName(editTemplateNameFormData, "templateDTO").then(res => {
    ElMessage({
      type: "success",
      message: "修改成功"
    });
    proTable.value?.clearSelection();
    proTable.value?.getTableList();
  });
  editTemplateNameDialogVisible.value = false;
};

const editSLA = async (params: any[]) => {
  if (params.length != 1) {
    ElMessage({
      type: "error",
      message: "只能编辑一条数据"
    });
    return;
  }
  if (params[0].templateType == "request") {
    //前往编辑页面
    tabStore.removeTabs(route.fullPath);
    router.push(
      `/system/tools/contentTemplateManagement/editRequestContentTemplate?pageNo=${Math.random().toFixed(3)}&id=` +
        params[0].templateId
    );
    return;
  }
  if (params[0].templateType == "problem") {
    //前往编辑页面
    tabStore.removeTabs(route.fullPath);
    router.push(
      `/system/tools/contentTemplateManagement/editProblemTemplateForm?pageNo=${Math.random().toFixed(3)}&id=` +
        params[0].templateId
    );
    return;
  }
  if (params[0].templateType == "change") {
    //前往编辑页面
    tabStore.removeTabs(route.fullPath);
    router.push(
      `/system/tools/contentTemplateManagement/editChangeTemplateForm?pageNo=${Math.random().toFixed(3)}&id=` +
        params[0].templateId
    );
    return;
  }
  if (params[0].templateType == "configureItem") {
    //前往编辑页面
    tabStore.removeTabs(route.fullPath);
    router.push(
      `/system/tools/contentTemplateManagement/editCiTemplateForm?pageNo=${Math.random().toFixed(3)}&id=` + params[0].templateId
    );
    return;
  }
  if (params[0].templateType == "knowledge") {
    //前往编辑页面
    tabStore.removeTabs(route.fullPath);
    router.push(
      `/system/tools/contentTemplateManagement/editKnowledgeTemplateForm?pageNo=${Math.random().toFixed(3)}&id=` +
        params[0].templateId
    );
    return;
  }
};
interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  lable: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}

// 删除
const deletebyService = async (index: any) => {
  console.log("sdaf");
};
// 删除相关服务
const deleteService = async (index: any) => {
  console.log("sdaf");
};

//添加相关服务列表
const addServiceList = async () => {
  console.log("sdaf");
};
//添加被服务机构
const addByService = async () => {
  console.log("sdaf");
};
</script>

<style scoped lang="scss">
.no-wrap {
  white-space: nowrap;
}
</style>
